package cn.fx.framework.utils;

import java.util.Random;
import java.util.UUID;

/**
 * 生成各种随机数：UUID，随机数字、字符或混合，随机中文，默认SnowflakeId
 */
public class RandomUtils {

    //设置一个默认的SnowflakeIdWorker,workerId:31,dataCenterId:31
    final static private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(31, 31);

    /**
     * 默认SnowflakeId生成器：workerId:31,dataCenterId:31
     * @return
     */
    public static long snowflakeId() {
        return snowflakeId(snowflakeIdWorker);
    }
    public static long snowflakeId( SnowflakeIdWorker worker) {
        return worker.nextId();
    }

    /**
     * 生成一个UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }

    //region 自定义生成字母数字随机数
    private final static Random randGen = new Random();
    private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
            + "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();

    private static char[] NUMBERS = ("01234567899876543210").toCharArray();

    /**
     * 生成大小写字母数字随机数
     * @param length 长度
     * @return
     */
    public static String randomString(int length) {
        return randomString(length, false);
    }

    /**
     * 生成大小写字母数字随机数
     *
     * @param length 长度
     * @param onlyForNumber 是否仅数字
     * @return
     */
    public static String randomString(int length, boolean onlyForNumber) {
        if (length < 1) {
            return null;
        }
        int numbersAndLettersSize = numbersAndLetters.length - 1;
        char[] chars = numbersAndLetters;
        if (onlyForNumber) {
            numbersAndLettersSize = NUMBERS.length - 1;
            chars = NUMBERS;
        }
        // Create a char buffer to put random letters and numbers in.
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            if (!onlyForNumber) {
                if (i % 5 == 0) {
                    //每5位生成一个纯数字;
                    randBuffer[i] = numbersAndLetters[randGen
                            .nextInt(10)];
                    continue;
                }
            }
            randBuffer[i] = chars[10 + randGen
                    .nextInt(numbersAndLettersSize - 10)];

        }
        return new String(randBuffer);
    }
    //endregion

    /**
     * 随机生成指定长度length的汉字字符
     *
     * @param length
     * @return
     */
    public static String randomChineseString(int length) {
        return ChineseUtils.generateFixLength(length);
    }

    public static void main(String[] args) {
        System.out.println("getUUID()：------------------" + getUUID());
        System.out.println("randomString(32)：-----------" + randomString(32));
        System.out.println("randomString(32, true)：-----" + randomString(32, true));
        System.out.println("randomChineseString(6)：-----" + randomChineseString(6));
        System.out.println("snowflakeId():--------------" + snowflakeId());
    }
}
